import React, {useState, useEffect, useRef, useMemo, useCallback} from 'react';
import {Select, Spin, Tag, Empty, Space} from 'antd';
import type {SelectProps} from 'antd';
import {Pageable} from '../utils/Page';
import {queryGoods, QueryGoodsResponse, queryGoodsSummariesByPage} from '../apis/GoodsApi';
import {debounce} from 'lodash';
import {number} from "prop-types";

const {Option} = Select;


interface GoodsWithSubGoodsSelectorProps {
    mode?: SelectProps["mode"]; // 选择模式
    value?: GoodsItem[]; // 选中的值
    onChange?: (value: GoodsItem[],) => void; // 值变化回调
    placeholder?: string;
    style?: React.CSSProperties;
    disabled?: boolean;
    id?: string;
    noSubGoods?: boolean
}

const PAGE_SIZE = 10;

export interface GoodsItem {
    barcode: string
    name: string
    id: number
    subGoodsId?: number
    subGoodsNumber?: string
}

export interface SelectedGoodsItem {
    id: number
    subGoodsId?: number
}

const GoodsWithSubGoodsSelector: React.FC<GoodsWithSubGoodsSelectorProps> = ({
                                                                                 id,
                                                                                 mode,
                                                                                 value = [],
                                                                                 onChange,
                                                                                 placeholder = '搜索商品或子商品...',
                                                                                 style,
                                                                                 disabled = false,
                                                                                 noSubGoods
                                                                             }) => {
    const [pageable, setPageable] = useState<Pageable>(new Pageable(1, PAGE_SIZE));
    const [data, setData] = useState<GoodsItem[]>([]);

    const [keyword, setKeyword] = useState('');
    const [loading, setLoading] = useState(false);
    const [hasMore, setHasMore] = useState(true);
    const currentRequestRef = useRef<number>(0);

    // 防抖搜索函数
    const handleSearch = useCallback(debounce((searchKeyword: string) => {
        setKeyword(searchKeyword);
        setPageable(new Pageable(1, PAGE_SIZE));
        setHasMore(true);
    }, 500), []);

    // 加载数据
    const loadData = useCallback(async (currentPageable: Pageable, currentKeyword: string) => {
        if (!hasMore) return;

        const requestId = Date.now();
        currentRequestRef.current = requestId;

        setLoading(true);
        try {

            const response = await queryGoodsSummariesByPage(currentPageable, {
                nameOrBarcode: currentKeyword || undefined
            });

            // 确保只处理最新的请求
            if (currentRequestRef.current !== requestId) return;

            const newData: GoodsItem[] = response.data.content.flatMap(item => {
                if (item.subGoodsList.length && !noSubGoods) {
                    return item.subGoodsList.map(subGoods => {
                        return {
                            id: item.id,
                            name: subGoods.name,
                            subGoodsId: subGoods.id,
                            subGoodsNumber: subGoods.number,
                            barcode: item.barcode,
                        }
                    })
                } else {
                    return [{
                        barcode: item.barcode,
                        name: item.name,
                        id: item.id
                    }]
                }
            })

            // 如果是第一页，替换数据；否则追加数据
            if (currentPageable.page === 1) {
                setData(newData);
            } else {
                setData(prev => [...prev, ...newData]);
            }

            setHasMore(!response.data.last);
        } catch (error) {
            console.error('加载商品数据失败:', error);
        } finally {
            setLoading(false);
        }
    }, [hasMore]);

    // 当搜索关键词或分页变化时重新加载数据
    useEffect(() => {
        loadData(pageable, keyword);
        console.log([...pageable.toDependencyList(), keyword])
    }, [...pageable.toDependencyList(), keyword]);

    // 滚动加载更多
    const handlePopupScroll = useCallback((e: React.UIEvent<HTMLDivElement>) => {
        const {scrollTop, scrollHeight, clientHeight} = e.currentTarget;

        // 滚动到底部时加载下一页
        if (scrollHeight - scrollTop <= clientHeight + 20 && !loading && hasMore) {
            setPageable(prev => new Pageable(prev.page + 1, prev.size));
        }
    }, [hasMore, loading]);

    // 处理选择变化
    const handleChange = useCallback((selectedValues: string[] | string) => {
        let values
        if (typeof selectedValues === "string") {
            values = [selectedValues]
        } else {
            values = selectedValues
        }

        if (!onChange) return;

        // 将字符串值转换为商品/子商品对象
        const selectedItems = (values.map(val => {
            return data.find(item => item.id === parseInt(val));
        }).filter(Boolean) as GoodsItem[]);
        onChange(selectedItems);
    }, [data, onChange]);

    // 渲染标签显示
    const tagRender = useCallback((props: any) => {
        const {value, closable, onClose} = props;
        if (!value) return <></>
        const idArray = value.split("-").map(parseInt)

        const item = data.find(item => (!!idArray[1] ? item.subGoodsId === idArray[1] : true) && item.id === idArray[0]);
        return (
            <Tag
                closable={closable}
                onClose={onClose}
                style={{marginRight: 3}}
            >
                {item?.name}
            </Tag>
        );
    }, [data]);

    // 获取当前值（字符串形式）
    const getValueString = useCallback(() => {
        return value.map(item => [item.id, item.subGoodsId].filter(Boolean).join("-"));
    }, [value]);
    return (
        <Select
            id={id}
            mode={mode}
            showSearch
            placeholder={placeholder}
            filterOption={false}
            onSearch={handleSearch}
            onChange={handleChange}
            onPopupScroll={handlePopupScroll}
            value={getValueString()}
            style={style}
            disabled={disabled}
            tagRender={tagRender}
            notFoundContent={
                loading ? <Spin size="small"/> :
                    data.length === 0 ? <Empty description="未找到商品"/> : null
            }
            dropdownRender={menu => (
                <>
                    {menu}
                    {loading && hasMore && (
                        <div style={{padding: '8px', textAlign: 'center'}}>
                            <Spin size="small"/>
                        </div>
                    )}
                </>
            )}
        >
            {data.map(item => {
                let key = [item.id, item.subGoodsId].filter(Boolean).join("-")
                return (
                    <Option
                        key={key}
                        value={key}
                    >
                        <Space>
                            <div>{item.name}</div>
                            {item.subGoodsNumber && <div style={{fontSize: 12, color: '#666'}}>
                                编号: {item.subGoodsNumber}
                            </div>}
                            <div style={{fontSize: 12, color: '#666'}}>
                                条码: {item.barcode}
                            </div>
                        </Space>
                    </Option>
                );
            })}
        </Select>
    );
};

export default GoodsWithSubGoodsSelector;

export interface GoodsSelectorProps {
    mode?: SelectProps["mode"]; // 选择模式
    value?: number[]; // 选中的值
    onChange?: (value: number[], data: GoodsSelectorItem[]) => void; // 值变化回调
    placeholder?: string;
    style?: React.CSSProperties;
    disabled?: boolean;
    id?: string;
    data?: GoodsSelectorItem[]
}

export interface GoodsSelectorItem {
    barcode: string
    name: string
    id: number
}

export const GoodsSelector: React.FC<GoodsSelectorProps> = (props) => {
    const items = useMemo(() => {
        return props.value?.map(it => props.data?.find(i => i.id === it)).filter(Boolean).map(it => it!!) ?? []
    }, [props.value, props.data])
    return <GoodsWithSubGoodsSelector {...props} noSubGoods value={items} onChange={value => {
        props.onChange?.(value.map(it => it.id), value)
    }}/>
}

